﻿using Framework;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.ResourceManagement.ResourceProviders;
using UnityEngine.SceneManagement;

namespace Game
{
    public class LoadSceneActionable : IBTreeActionable<SceneBTreeContext>
    {
        private AsyncOperationHandle<SceneInstance> _handle;
        private SceneBTreeContext _context;
        
        public void OnStart(SceneBTreeContext context)
        {
            _context = context;
            _handle = Addressables.LoadSceneAsync(_context.sceneData.url, LoadSceneMode.Additive);
            _handle.Completed += OnLoadSceneCompleted;
        }

        public void OnEnd(SceneBTreeContext context)
        {
        }

        public TaskStatus Update(SceneBTreeContext context)
        {
            if (_handle.IsDone)
            {
                return TaskStatus.Success;    
            }

            return TaskStatus.Running;
        }

        private void OnLoadSceneCompleted(AsyncOperationHandle<SceneInstance> handle)
        {
            _context.sceneEntity = SceneSystem.Instance.CreateScene(_handle.Result, _context.sceneData);
            SceneSystem.Instance.SetSceneActive(_context.sceneData.name, true);
        }
    }
}